<script setup lang="ts">
import { getMemberProfileAPI, putMemberProfileAPI } from '@/services/profile'
import { useMemberStore } from '@/stores'
import type { Gender, ProfileDetail } from '@/types/member'
import { onLoad } from '@dcloudio/uni-app'
import { ref,reactive } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 表单引用
const form = ref();
const errorType = ref('toast');
// 获取个人信息，修改个人信息需提供初始值
const profile = ref({} as ProfileDetail)
const state = reactive<{formModel: ProfileDetail,  rules: object}>({
  formModel: {
    id: 0,
    avatar: '',
    account: '',
    nickname: '',
    birthday: '',
    fullLocation: '',
    profession: ''
  },
  rules: {
    'nickname': [
      {
        type: 'string',
        required: true,
        message: '请填写昵称',
        trigger: ['blur', 'change'],
      },{
        validator: (rule:any, value:string) => {
          return uni.$u.test.chinese(value);
        },
        message: "昵称必须为中文",
        trigger: ["change", "blur"],
      }
    ],
    'profession': {
      type: 'string',
      required: true,
      message: '请填写职业',
      trigger: ['blur', 'change']
    }
  }
});
const getMemberProfileData = async () => {
  const res = await getMemberProfileAPI()
  profile.value = res.result
  state.formModel = profile.value
  // 同步 Store 的头像和昵称，用于我的页面展示
  memberStore.profile!.avatar = res.result.avatar
  memberStore.profile!.nickname = res.result.nickname
}

onLoad(() => {
  getMemberProfileData()
})

const memberStore = useMemberStore()
// 修改头像
const onAvatarChange = () => {
  // 调用拍照/选择图片
  // 选择图片条件编译
  // #ifdef H5 || APP-PLUS
  // 微信小程序从基础库 2.21.0 开始， wx.chooseImage 停止维护，请使用 uni.chooseMedia 代替
  uni.chooseImage({
    count: 1,
    success: (res) => {
      // 文件路径
      const tempFilePaths = res.tempFilePaths
      // 上传
      uploadFile(tempFilePaths[0])
    },
  })
  // #endif

  // #ifdef MP-WEIXIN
  // uni.chooseMedia 仅支持微信小程序端
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      // 本地路径
      const { tempFilePath } = res.tempFiles[0]
      // 上传
      uploadFile(tempFilePath)
    },
  })
  // #endif
}

// 文件上传-兼容小程序端、H5端、App端
const uploadFile = (file: string) => {
  // 文件上传
  uni.uploadFile({
    url: '/member/profile/avatar',
    name: 'file',
    filePath: file,
    success: (res) => {
      if (res.statusCode === 200) {
        const avatar = JSON.parse(res.data).result.avatar
        // 个人信息页数据更新
        profile.value!.avatar = avatar
        // Store头像更新
        memberStore.profile!.avatar = avatar
        uni.showToast({ icon: 'success', title: '更新成功' })
      } else {
        uni.showToast({ icon: 'error', title: '出现错误' })
      }
    },
  })
}

// 修改性别
const onGenderChange: UniHelper.RadioGroupOnChange = (ev) => {
  profile.value.gender = ev.detail.value as Gender
}

// 修改生日
const onBirthdayChange: UniHelper.DatePickerOnChange = (ev) => {
  profile.value.birthday = ev.detail.value
}

const showBirthday = ref(false);
const birthdayConfirm = (e:any)=> {
  showBirthday.value = false
  state.formModel.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
}

// 修改城市
let fullLocationCode: [string, string, string] = ['', '', '']
const onFullLocationChange: UniHelper.RegionPickerOnChange = (ev) => {
  // 修改前端界面
  profile.value.fullLocation = ev.detail.value.join(' ')
  state.formModel.fullLocation = profile.value.fullLocation
  // 提交后端更新
  fullLocationCode = ev.detail.code!
}

// 点击保存提交表单
const onSubmit = async () => {
  const { nickname, gender, birthday } = profile.value
  form.value.validate().then(async (valid: boolean) => {
    if (valid) {
      const res = await putMemberProfileAPI({
        nickname,
        gender,
        birthday,
        provinceCode: fullLocationCode[0],
        cityCode: fullLocationCode[1],
        countyCode: fullLocationCode[2],
      })
      // 更新Store昵称
      memberStore.profile!.nickname = res.result.nickname
      uni.showToast({ icon: 'success', title: '保存成功' })
      setTimeout(() => {
        uni.navigateBack()
      }, 400)
    }
  });
}

</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view @tap="onAvatarChange" class="avatar-content">
        <image class="image" :src="profile?.avatar" mode="aspectFill" />
        <text class="text">点击修改头像</text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="form">
      <view class="form-content">
        <up-form
          labelPosition="left"
          :model="state.formModel"
          :rules="state.rules"
          :errorType="errorType"
          ref="form"
        >
          <up-form-item
            label="账号"
            borderBottom
          >
            <up-text :text="state.formModel.account"></up-text>
          </up-form-item>
          <up-form-item
            label="昵称"
            prop="nickname"
            borderBottom
          >
            <up-input
              v-model="state.formModel.nickname"
              border="none"
            ></up-input>
          </up-form-item>
          <up-form-item
            label="性别"
            prop="gender"
            borderBottom
          >
            <up-radio-group
              v-model="state.formModel.gender"
              placement="row"
            >
              <up-radio
                :customStyle="{marginRight: '18px'}"
                v-for="(item, index) in [{name:'男',value:'男'},{name:'女',value:'女'}]"
                :key="index"
                :label="item.name"
                :name="item.name"
              >
              </up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item
            label="生日"
            prop="birthday"
            @click="showBirthday=true"
            borderBottom
          >
            <up-input
              v-model="state.formModel.birthday"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择生日"
              border="none"
            ></up-input>
            <up-icon
              slot="right"
              name="arrow-right"
            ></up-icon>
          </up-form-item>
          <!-- #ifdef MP-WEIXIN -->
          <up-form-item
            label="城市"
            prop="fullLocation"
            borderBottom
          >
            <picker
              @change="onFullLocationChange"
              mode="region"
              class="picker"
              :value="state.formModel?.fullLocation?.split(' ')"
            >
              <view v-if="state.formModel?.fullLocation">{{ state.formModel.fullLocation }}</view>
              <view class="placeholder" v-else>请选择城市</view>
            </picker>
          </up-form-item>
          <!-- #endif -->
          <up-form-item
            label="职业"
            prop="profession"
            borderBottom
          >
            <up-input
              v-model="state.formModel.profession"
              border="none"
            ></up-input>
          </up-form-item>
        </up-form>
      </view>
      <up-datetime-picker
        :show="showBirthday"
        :minDate="(new Date('1900-01-01')).getTime()"
        :maxDate="(new Date()).getTime()"
        mode="date"
        closeOnClickOverlay
        @confirm="birthdayConfirm"
        @cancel="showBirthday=false"
        @close="showBirthday=false"
      ></up-datetime-picker>
      <!-- 提交按钮 -->
      <button @tap="onSubmit" class="form-button">保 存</button>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}
</style>
